
/**
 * 写入缓存
 *
 * 全部都会加密,
 * 都会先转成json
 *
 * expired 过期时间 s
 *  -1 永不过期
 *
 */

import base64 from './base64'
import store from '../store'

export const save = (key, data, expired = -1) => {
  if (!data || data === null) {
    return
  }
  const obj = {
    data,
    expired: expired > -1 ? expired * 1000 + new Date().getTime() : -1
  }
  uni.setStorageSync(key, base64.encode(obj))
}

export const get = (key) => {
  const value = uni.getStorageSync(key)
  if (!value || value === null) {
    return null
  }
  const obj = base64.parse(value)
  const { data, expired } = obj
  if (expired > -1 && expired < new Date().getTime()) {
    remove(key)
    return null
  }
  return data
}

export const remove = (key) => {
  return uni.removeStorageSync(key)
}

// 清除全部
export const clearAll = () => {
  const token = store.getters['User/token']
  const info = store.getters['User/info']
  uni.clearStorageSync()
  store.dispatch('User/login', token).then()
  store.dispatch('User/set_info', info).then()

  // 把地址设为null
  store.dispatch('Address/set_data', null)
}
